<template>
    <el-drawer :title="title" :visible.sync="visible" size="644px" append-to-body custom-class="custom-drawer">
        <el-form ref="form" :model="form" :rules="rules" size="medium" label-width="156px" style="flex: 1;" @submit.native.prevent>
            <el-form-item :label="parentLabel">
                <el-input v-model="form.parent" disabled></el-input>
            </el-form-item>

            <el-form-item v-if="level > 1" label="上级清单子目编码">
                <el-input v-model="parentCode" disabled></el-input>
            </el-form-item>
            <el-form-item v-if="level > 1" label="上级清单子目名称">
                <el-input v-model="parentName" disabled></el-input>
            </el-form-item>

            <el-form-item prop="listSubitemCode">
                <div v-if="type === 1" slot="label" style="display: inline-block;">
                    <span>清单子目编码 </span>
                    <el-tooltip effect="dark" content="从所属章次的数值继续开始编号，仅允许输入数字，最少3位数字，不可与章次数值一致，不能为空" placement="top">
                        <i class="el-icon-info"></i>
                    </el-tooltip>
                </div>
                <div v-if="type === 2" slot="label" style="display: inline-block;">
                    <span>清单子目编码 </span>
                </div>
                <el-input v-if="type === 1" v-model="form.listSubitemCode" maxlength="200" clearable placeholder="请输入"></el-input>
                <el-input v-if="type === 2" v-model="form.listSubitemCode" maxlength="200" clearable placeholder="请输入，包含数字、字母横杠-，数字开头和数字结尾，不能为0"></el-input>
            </el-form-item>
            <el-form-item label="清单子目名称" prop="listSubitemName">
                <el-input v-model="form.listSubitemName" maxlength="50" show-word-limit clearable placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item prop="isChild">
                <div slot="label" style="display: inline-block;">
                    <span>是否存在下级子项 </span>
                    <el-tooltip effect="dark" content="当前清单子目是否存在下一级清单子目" placement="top">
                        <i class="el-icon-info"></i>
                    </el-tooltip>
                </div>
                <el-radio-group v-model="form.isChild" @change="handleChangeIsChild">
                    <el-radio :label="1">存在</el-radio>
                    <el-radio :label="2">不存在</el-radio>
                </el-radio-group>
            </el-form-item>
            <template v-if="form.isChild === 1">
                <el-form-item label="单位">
                    <el-input v-model="form.unitSymbol" disabled placeholder="当前子目存在下级子项时，不可维护单位、数量、单价" clearable></el-input>
                </el-form-item>
                <el-form-item label="数量">
                    <el-input v-model="form.quantity" disabled placeholder="当前子目存在下级子项时，不可维护单位、数量、单价" clearable></el-input>
                </el-form-item>
                <el-form-item label="单价（元）">
                    <el-input v-model="form.price" disabled placeholder="当前子目存在下级子项时，不可维护单位、数量、单价" clearable></el-input>
                </el-form-item>
                <el-form-item label="合价（元）">
                    <el-input v-model="amount" disabled></el-input>
                </el-form-item>
            </template>
            <div v-if="form.isChild === 2">
                <el-form-item prop="unitCode">
                    <div slot="label" style="display: inline-block;">
                        <span>单位 </span>
                        <el-tooltip effect="dark" content="如果有单位缺失，请联系亮风台人员添加" placement="top">
                            <i class="el-icon-info"></i>
                        </el-tooltip>
                    </div>
                    <el-select
                        v-model="form.unitCode"
                        placeholder="请选择"
                        filterable
                        clearable
                        style="width: 100%;"
                        @change="handleChangeUnit"
                    >
                        <el-option
                            v-for="item in unitOptions"
                            :key="item.unitCode"
                            :label="item.unitSymbol"
                            :value="item.unitCode"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="数量" prop="quantity">
                    <el-input v-model="form.quantity" :disabled="!form.unitSymbol" :placeholder="!form.unitSymbol ? '请先选择单位' : quantityPlaceholder" clearable></el-input>
                </el-form-item>
                <el-form-item label="单价（元）" prop="price">
                    <el-input v-model="form.price"  :disabled="!form.unitSymbol" :placeholder="!form.unitSymbol ? '请先选择单位' : '请输入单价，可保留两位小数'" clearable></el-input>
                </el-form-item>
                <el-form-item>
                    <div slot="label" style="display: inline-block;">
                        <span>合价（元） </span>
                        <el-tooltip effect="dark" content="录入数量、单价后，系统自动合价" placement="top">
                            <i class="el-icon-info"></i>
                        </el-tooltip>
                    </div>
                    <el-input v-model="amount" disabled></el-input>
                </el-form-item>
            </div>

            <el-form-item label="备注">
                <el-input
                    v-model="form.remark"
                    type="textarea"
                    :autosize="{ minRows: 2, maxRows: 4}"
                    placeholder="请输入"
                    maxlength="100"
                    show-word-limit
                >
                </el-input>
            </el-form-item>
        </el-form>

        <div class="dialog-footer">
            <BaseButton type="recond" @click="cancel">取消</BaseButton>
            <BaseButton :loading="submitLoading" @click="submitForm">提交</BaseButton>
        </div>
    </el-drawer>
</template>

<script>
import { ProjectLedgerModel } from '@/models'
import { isNumber2 } from '@/utils/validate'
import BigNumber from 'bignumber.js'

const validIsNumber2 = (rule, value, callback) => {
    if (!isNumber2(value)) {
        callback(new Error('格式错误'))
    } else {
        callback()
    }
}

export default {
    name: 'ChildSaveOrUpdate',
    props: {
        type: {
            type: Number,
            default: 1 // type=1:普通工程量清单；type=2:计日工
        },
    },
    data() {
        return {
            parentLabel: '所属章次',
            model: new ProjectLedgerModel(),
            title: '',
            visible: false,
            submitLoading: false,
            // 表单参数
            form: {
                parent: '',
                listSubitemCode: '',
                listSubitemName: '',
                isChild: 1,
                unitCode: null,
                quantity: '',
                price: '',
                level: 1,
                remark: ''
            },
            level: 1,
            projectId: 1,
            parentCode: '',
            parentName: '',
            chapterSequenceCode: '',
            unitValidateDecimalPlace: 0,
            quantityPlaceholder: '请输入',
            rules: {
                listSubitemCode: [],
                listSubitemName: [{ required: true, message: '请输入', trigger: 'blur' }],
                isChild: [{ required: true, message: '请选择', trigger: 'change' }],
                unitCode: [{ required: true, message: '请选择', trigger: 'change' }],
                quantity: [
                    { required: true, message: '请输入', trigger: 'blur' },
                    { validator: this.validQuantity, trigger: 'blur' }
                ],
                price: [
                    { required: true, message: '请输入', trigger: 'blur' },
                    { validator: validIsNumber2, trigger: 'blur' }
                ]
            },
            unitOptions: []
            
        }
    },
    computed: {
        amount() {
            const { quantity, price} = this.form
            if ((!quantity && quantity !== '0') || (!price && price !== '0')) {
                return ''
            }
            const total = new BigNumber(this.form.quantity).times(this.form.price).toFixed(2)
            return total
        }
    },
    created () {
        this.getUnitList()
        // 处理下名称
        if (this.type === 1) {
            this.parentLabel = '所属章次'
        }
        if (this.type === 2) {
            this.parentLabel = '分类'
        }
    },
    methods: {
        // 取消按钮
        cancel() {
            this.reset()
            this.visible = false
        },
        open(options = {}) {
            const { type: pageType, projectId, parentCode, parentName, pName, chapterSequenceCode, level, row } = options
            this.projectId = projectId
            this.parentCode = parentCode
            this.parentName = parentName
            this.chapterSequenceCode = chapterSequenceCode
            this.visible = true
            this.reset()

            if (pageType === 'edit') {
                this.form = {...row, isChild: row.hasChildren }
            }
            // 如果是第一级和其他层级，验证规则不一样，验证规则要写在前面，否则不生效
            if (level === 1) {
                // 工程量和计日工验证规则不一样
                if (this.type === 1) {
                    this.rules.listSubitemCode = [
                        { required: true, message: '请输入', trigger: 'blur' },
                        { validator: this.validCode1, trigger: 'blur' },
                        { validator: this.validCodeUnique, trigger: 'blur' }
                    ]
                }
                if (this.type === 2) {
                    this.rules.listSubitemCode = [
                        { required: true, message: '请输入', trigger: 'blur' },
                        { validator: this.validCode3, trigger: 'blur' },
                        { validator: this.validCodeUnique, trigger: 'blur' }
                    ]
                }
                if (pageType === 'add') {
                    this.title = '新增一级清单子目'
                }
                if (pageType === 'edit') {
                    this.title = '编辑一级清单子目'
                }
            } else {
                // 工程量和计日工验证规则不一样
                if (this.type === 1) {
                    this.rules.listSubitemCode = [
                        { required: true, message: '请输入', trigger: 'blur' },
                        { validator: this.validCodeUnique, trigger: 'blur' },
                        { validator: this.validCode2, trigger: 'blur' }
                    ]
                }
                if (this.type === 2) {
                    this.rules.listSubitemCode = [
                        { required: true, message: '请输入', trigger: 'blur' },
                        { validator: this.validCodeUnique, trigger: 'blur' },
                        { validator: this.validCode3, trigger: 'blur' }
                    ]
                }
                
                // 如果是子项的新增，且为工程量清单1，子项编码要继承父级的
                if (pageType === 'add') {
                    this.title = '新增下级清单子目'
                    if (this.type === 1) {
                        this.form.listSubitemCode = parentCode + '-'
                    }
                }
                if (pageType === 'edit') {
                    this.title = '编辑下级清单子目'
                }
            }
            // 回填下用于显示的第一级章次/分类名称
            this.form.parent = pName
            this.level = level

            // 重置下验证规则
            this.$nextTick(() => {
                this.$refs['form'].clearValidate()
            })
        },
        reset() {
            this.form = {
                parent: '',
                listSubitemCode: '',
                listSubitemName: '',
                isChild: 1,
                unitCode: null,
                quantity: '',
                price: '',
                level: 1,
                remark: ''
            }
        },
        submitForm() {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    this.submitLoading = true
                    const data = {
                        ...this.form,
                        parentCode: this.parentCode,
                        parentName: this.parentName,
                        chapterSequenceCode: this.chapterSequenceCode,
                        projectId: this.projectId,
                        msType: 2,
                        type: this.type,
                        level: this.level,
                        unitSymbol: this.form.unitSymbol,
                    }
                    this.model
                        .childSaveOrUpdate(data)
                        .then(() => {
                            this.$message({
                                type: 'success',
                                message: '操作成功！',
                                duration: 500,
                                onClose: () => {
                                    this.visible = false
                                    this.$emit('success')
                                }
                            })
                        })
                        .finally(() => {
                            this.submitLoading = false
                        })
                }
            })
        },
        getUnitList() {
            this.model.unitList().then(res => {
                this.unitOptions = res || []
            })
        },
        handleChangeUnit(value) {
            const target = this.unitOptions.find(item => item.unitCode === value) || {}
            this.unitValidateDecimalPlace = target.decimalPlace
            this.form.unitSymbol = target.unitSymbol
            if (this.unitValidateDecimalPlace === 0) {
                this.quantityPlaceholder = '请输入数量，保留整数'
            } else {
                this.quantityPlaceholder = `请输入数量，可保留${this.unitValidateDecimalPlace}位小数`
            }
        },
        validCode1(rule, value, callback) {
            // 是否为数字且至少3位
            const regex = /^\d{3,}$/
            if (!regex.test(value)) {
                callback(new Error('格式错误'))
            } else if (value <= this.parentCode) {
                callback(new Error('格式错误'))
            } else {
                callback()
            }
        },
        validCode2(rule, value, callback) {
            const regex = /^[1-9][0-9]*(-[0-9]+)*$/
            if (!regex.test(value)) {
                callback(new Error('格式错误'))
            } else {
                callback()
            }
        },
        validCode3(rule, value, callback) {
            const regex = /^[1-9]\d*(-\d+)*$/
            if (!regex.test(value)) {
                callback(new Error('格式错误'))
            } else {
                callback()
            }
        },
        validQuantity(rule, value, callback) {
            console.log('validQuantity')
            const regex = this.createDecimalRegex(this.unitValidateDecimalPlace)
            if (!regex.test(value)) {
                callback(new Error('格式错误'))
            } else {
                callback()
            }
        },
        validCodeUnique(rule, value, callback) {
            this.model.validQuantitiesUnique({
                code: value,
                id: this.form.id || null,
                projectId: this.projectId,
                type: this.type,
                msType: 2
            }).then((res) => {
                if (!res) {
                    callback(new Error('清单子目编码已存在'))
                } else {
                    callback()
                }
            })
        },
        createDecimalRegex(places) {
            if (places === 0) {
                return /^\d+$/
            }
            // 生成对应位数小数的正则表达式字符串
            const decimalPart = `(?:\\.(\\d{1,${places}}))?`
            const regexStr = `^\\d+${decimalPart}$`            
            return new RegExp(regexStr)
        },
        handleChangeIsChild() {
            this.unitValidateDecimalPlace = 0
            this.form.unitCode = null
            this.form.unitSymbol = ''
            this.form.quantity = ''
            this.form.price = ''
        }
    }
}
</script>
<style lang="scss">
.custom-drawer {
    .el-drawer__header {
        border-bottom: 1px solid #eee;
        padding: 24px;
        color: #171725;
    }
    .el-drawer__body {
        display: flex;
        flex-direction: column;
        padding: 0 24px;
    }
    .el-drawer__close-btn {
        font-size: 22px;
    }
}
</style>
<style lang="scss" scoped>
.dialog-footer {
    padding: 24px;
    text-align: right;
    border-top: 1px solid #eee;
}
</style>
